#coding:utf-8
'''
create on 2017-07-15

@author: sandy
'''

from twisted.internet import task
import HallConfig
import logging
import importlib
import Center
import CenterBuild

class HallManager(object):
    
    def __init__(self):
        self.lstHall = []
    
    def start(self):
        hallconfigs = HallConfig.instance.getHallConfig()
        if not hallconfigs:
            logging.error("no halls")
            return
        hid = 0
        for hc in hallconfigs:
            hid += 1
            hall = None
            try:
                hall = self.createHall(hid, hc)
            except Exception:
                logging.exception("HallManager.createHall()") 
                continue
            if not hall:
                logging.error("createHall(%d) return None", hid) 
                continue
            self.lstHall.append(hall)

        l = task.LoopingCall(self.onTimer)
        l.start(20, False)
        
    def onTimer(self):
        result = {}
        for hall in self.lstHall:
            hid = hall.hid
            usedTableCount = 0
            for t in hall.tablemap.values():
                if False == t.isEmptySeat():
                    usedTableCount += 1
            result[hid] = usedTableCount
        Center.instance.sendPacket(CenterBuild.reportHallOnline(result))
        pass
    
    def stop(self):
        pass
    
    def createHall(self, hid, hc):
        htype = hc.get(u"type")
        mo = importlib.import_module("Hall"+htype)
        return mo.create(hid, hc)
    
    def getHall(self, hid):
        iHall = hid - 1
        if 0 > iHall or len(self.lstHall) <= iHall:
            return None
        return self.lstHall[iHall]
    
    def getAllHallInfo(self):
        l = []
        for h in self.lstHall:
            d = h.getHallInfo()
            if not d:
                continue
            l.append(d)
        return l
    
    def getAllHall(self):
        return self.lstHall
    

instance = HallManager()

if __name__ == '__main__':
    pass